# Copyright (c) 2012 Nathan Grubb
# Available under the new BSD license; see LICENSE.txt

"""plugin/evaluate.py: An example command plugin which simply evaluates arguments
   as Python expressions. The simplest default plugin to help inexperienced plugin
   programmers to write new plugins. Heavily commented.
"""

class Eval(object):
    # The type of plugin ("irc" or "command".) Commands plugins are a simpler, 
    # more abstracted type of plugin used exclusively for bot commands.
    type = "command"
    # A dict of bot commands this plugin responds to, and their minimum arguments.
    # A corresponding function (called "command_$COMMAND") is expected to exist
    # and is called whenever the bot command is used with at least the minimum
    # number of arguments and permissions are correct
    commands = {"eval": 1,}
    # The type of permissions (either "admin", "op", or None.) Admins have
    # ultimate permissions and can use any plugin; ops can use any plugin with
    # permissions of "op" or None. Everyone else can only use plugins with
    # permissions of None
    permissions = "admin"
    # The name of the plugin. Used only for information by the help plugin.
    name = "Evaluate"
    # The description of the plugin. Used only for information by the help plugin.
    desc = "Evaluates expressions"
    
    def __init__(self, api, msg):
        # Api: an instance of lib.plugin.PluginApi. Contains a lot of helpful
        # functions for plugins to use. Also contains access to the program's
        # state holder, grubbot.Grubbot.
        self.api = api
        # An instance of lib.message.Message, which has been instiated with
        # the details of the IRC message that brought up this plugin.
        self.msg = msg

    def command_eval(self, args):
        """Corresponding to the command "eval", this function is called
           whenever the command "eval" is used in a channel. It is also passed
           all the arguments given. It is now up to the function to decide
           what to do with this information.
        """

        expression = " ".join(args)
        result = str(eval(expression))

        # A call to the API function reply, which needs to be passed the 
        # Message object given to the plugin initially to determine the
        # correct channel to send the reply. The second argument is the actual
        # reply which the plugin generates. Do not worry about multi-lined
        # results because the reply function knows how to handle them.
        self.api.reply(self.msg, result)

plugin = Eval